package de.amoerke.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidChatActivity extends Activity {
	private final int mSocketPortNumber = 8080;
	private final String mSocketAddress= "http://109.73.51.13:8080/CometChat/Chat";
	private final String mSocketAddressLocal= "http://192.168.1.102:8080/CometChat/Chat";
	private Socket mSocket;
	private volatile BufferedReader mBufferedReader;	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button sendBtn = (Button) findViewById(R.id.btn_send);
        
        sendBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final EditText srcTxt = (EditText) findViewById(R.id.message); 
				sendMessageToServer(String.valueOf(srcTxt.getText()));				
			}
		});        
    }    
    
    private void sendMessageToServer(String msg)
    {
    	HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(mSocketAddressLocal);

        try {        	
            StringEntity se = new StringEntity( msg, HTTP.UTF_8);
            se.setContentType("text/plain");
            httppost.setEntity(se);

            HttpResponse httpresponse = httpclient.execute(httppost);
            HttpEntity resEntity = httpresponse.getEntity();
            final String responseString = EntityUtils.toString(resEntity);
            final TextView edt = (TextView) findViewById(R.id.response);
            edt.setText(responseString);
            Log.d("init", responseString);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}